from django.shortcuts import render
from myapp.models import *
import json
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from .serializer import *
from myapp.serializer import *
from decorator.decorator import check_login
from datetime import datetime
from django.db import transaction
from alipay import AliPay
from django.conf import settings
import time,random
from django.shortcuts import redirect
# Create your views here.


# 购物车
class ShoppingModelView(ModelViewSet):
    queryset = Shopping.objects.all()
    serializer_class = ShoppingSer

    # 获取购物车信息
    @check_login
    def list(self, request, *args, **kwargs):
        uid = request.user
        user_id = uid.id
        print('user_id>', user_id)
        if not user_id:
            return Response({
                "code": 204,
                "msg": "请先登录！"
            })
        shopp = Shopping.objects.filter(user_id=user_id).all()
        shopp_ser = ShoppingSer(shopp, many=True).data
        shopp_ser = json.loads(json.dumps(shopp_ser))
        for i in shopp_ser:
            dishes = Dishes.objects.filter(id=i['dishes_id']).first()
            dishes = DishesSer(dishes).data
            dishes = json.loads(json.dumps(dishes))
            i['dishes'] = dishes
        return Response({"msg":"获取成功", "code": 200, "data": shopp_ser})

    # 添加购物车
    def create(self, request, *args, **kwargs):
        try:
            cid = request.data.get('id')
            uid = request.data.get("uid")
            print("用户id", uid)
            print('菜》》', cid)
            if not uid:
                return Response({'code': 204, "msg":"请先登录！"})
            dish = Dishes.objects.filter(id=cid).all()
            for i in dish:
                Shopping.objects.create(user_id_id=uid,dishes_id_id=cid, merchant_id_id=i.merchant_id_id)
                return Response({"code":200, "msg":"加入购物车成功"})
        except Exception as e:
            print('错误>>', e)
            return Response({"code":500, "msg": "服务器错误"})

    # 删除购物车数据
    def destroy(self, request, *args, **kwargs):
        cid = self.get_object()
        if cid:
            self.get_object().delete()
            return Response({
                'code':200,
                'msg':"删除购物车商品成功"
            })
        else:
            return Response({
                'code':204,
                'msg':"没有获取到购物车信息"
            })


# 购物车菜品数量增加
class ShoppOneJia(APIView):
    def post(self, request, id):
        try:
            uid = request.data.get('uid')
            cid = request.data.get('cid')
            print('uid', uid)
            print('cid', cid)
            # 根据商品id查询商品对象
            cart = Shopping.objects.filter(user_id=uid, id=cid).first()
            if cart:
                count = cart.num
                Shopping.objects.filter(id=id).update(num=count + 1)
                return Response({'code': 200, 'msg': "加购成功 数量家加一"})
        except Exception as e:
            print("错误>>", e)
            return Response({"code": 500, "msg":"服务器错误"})


# 购物车菜品数量减少
class ShoppJian(APIView):
    def post(self, request,id):
        try:
            uid = request.data.get('uid')
            cid = request.data.get('cid')
            print('uid', uid)
            print('cid', cid)
            # 根据商品id查询商品对象
            cart = Shopping.objects.filter(user_id=uid, id=cid).first()
            if cart:
                count = cart.num
                if count > 1:
                    Shopping.objects.filter(id=id).update(num=count - 1)
                    return Response({'code': 200, 'msg': "数量减一"})
                return Response({
                    "code": 204,
                    "msg": "在减了就没有了哦！"
                })
        except Exception as e:
            print("错误>>", e)
            return Response({"code": 500, "msg":"服务器错误"})



# 读取app 私钥
app_private_key_string = open(settings.APP_PRIVATE_KEY_PATH,'r').read()

# 读取支付宝公钥
alipay_public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH,'r').read()

# 定义自己的视图类
class MyAlipay(APIView):
    def __init__(self, *args, **kwargs):
        # 继承父类的初始化部分
        super().__init__(*args, **kwargs)

        # 自己定义
        self.alipay = AliPay(
            appid='2021000119634123',
            app_private_key_string=app_private_key_string,
            alipay_public_key_string=alipay_public_key_string,
            app_notify_url=None,
            sign_type='RSA2',
            debug=True, # 所有的请求 定向到沙箱服务
        )

    def get_pay_url(self, order_id, total_amount):
        # 订单字符串
        order_string = self.alipay.api_alipay_trade_page_pay(
            subject="商家收款",
            out_trade_no=order_id,
            total_amount=total_amount,
            return_url="http://127.0.0.1:8000/customer/pay/",
            notify_url="http://127.0.0.1:8000/customer/pay/",
        )

        # 支付地址
        return 'https://openapi.alipaydev.com/gateway.do?' + order_string


# 订单类的视图
class OrderAPIView(MyAlipay):
    def post(self, request):
        add_id = request.data.get("add_id")
        uid = request.data.get("uid")
        monye = request.data.get("monye")
        print('地址:', add_id)
        print('用户:', uid)
        print("总价", monye)
        order_id = str(time.time())+ str(uid)+ str(random.randint(100000,999999))
        print('order>>', order_id)
        userinfo = Shopping.objects.filter(user_id=uid).all()
        mesh_id = Shopping.objects.filter(user_id=uid).first()
        merchant = mesh_id.merchant_id_id
        print('merchant>>', merchant)
        # print('iii', userinfo)
        try:
            num = 0
            for i in userinfo:
                num += int(num + i.num)
            order = Order.objects.create(order_id=order_id,user_id_id=uid,address_id_id=add_id, price=monye,order_num=num, merchant_id=merchant)
            for i in userinfo:
                print('id', i.dishes_id_id)
                orgoods = OrderGoods.objects.create(order_id_id=order.id,user_id_id=uid,dishes_id_id=i.dishes_id_id,num=i.num, merchant_id=i.merchant_id_id)
                print('good_id>>', orgoods.dishes_id_id)
            user_order = Order.objects.filter(user_id=uid).all()

            if user_order:
                for i in user_order:
                    Shopping.objects.filter(user_id=i.user_id_id).delete()
                    total_amount = float(monye)
                    pay_url = self.get_pay_url(order_id, total_amount)
            print(pay_url)
            return Response({'code': 200, 'msg': '创建订单成功正在跳转支付页面...', 'url': pay_url})
        except Exception as e:
            print("错误》",e)
            return Response({"code":500, "msg":"服务器错误"})


# 校验订单是否支付成功
class Checkout(MyAlipay):
    def get(self, request):
        # 获取订单id
        order_id = request.query_params.get("out_trade_no")
        pay_result = self.alipay.api_alipay_trade_query(order_id)

        order = Order.objects.filter(order_id=order_id).first()
        # 获取支付状态
        trade_status = pay_result.get("trade_status")
        if trade_status == 'TRADE_SUCCESS':
            # 支付成功
            status = 5
            order.status = 5
            order.save()
        else:
            # 支付失败
            status = 1

        # 跳转前端订单页面
        return redirect('http://localhost:8080/order_from')


# 未支付的定义支付
class Unpaid(MyAlipay):
    def post(self, request):
        try:
            oid = request.data.get('oid')
            uid = request.data.get("uid")
            print('用户》》》》', uid)
            print('订单》》》》', oid)
            if not uid:
                return Response({
                    "code": 204,
                    "msg": "请先登录！"
                })
            order_into = Order.objects.filter(id=oid).first()
            monye = order_into.price
            order_id = order_into.order_id
            print("价格》》》》", monye)
            print("订单》》》》", order_id)
            total_amount = float(monye)
            pay_url = self.get_pay_url(order_id, total_amount)
            print(pay_url)
            return Response({'code': 200, 'msg': '正在跳转支付页面...', 'url': pay_url})

        except Exception as e:
            print("错误>>>", e)
            return Response({"code":500, "msg":"服务器错误"})